package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.config.CrmebConfig;
import com.zbkj.common.constants.SysConfigConstants;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.MerchantGeneralType;
import com.zbkj.common.model.brand.Brand;
import com.zbkj.common.model.merchant.MerchantCategory;
import com.zbkj.common.model.page.PageDiy;
import com.zbkj.common.model.system.SystemConfig;
import com.zbkj.common.model.system.SystemFormTemp;
import com.zbkj.common.request.*;
import com.zbkj.common.response.GoodsLocationAllianceTypeResponse;
import com.zbkj.common.response.GoodsLocationResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.common.vo.MyRecord;
import com.zbkj.service.dao.SystemConfigDao;
import com.zbkj.service.service.*;
import com.zbkj.service.util.BrandUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * SystemConfigServiceImpl 接口实现
 +----------------------------------------------------------------------
 */
@Service
@Slf4j
public class SystemConfigServiceImpl
        extends ServiceImpl<SystemConfigDao, SystemConfig> implements SystemConfigService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SystemConfigDao dao;

    @Autowired
    private SystemFormTempService systemFormTempService;

    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CrmebConfig crmebConfig;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SystemAdminService adminService;
    @Autowired
    private MerchantCategoryService categoryService;
    @Autowired
    private MerchantGeneralTypeService merchantGeneralTypeService;


    /**
     * 在系统启动初始化时
     * 根据配置文件加载config_list缓存
     */
    @PostConstruct
    public void loadingConfigCache() {
        if (!crmebConfig.getAsyncConfig()) {
            return;
        }
        if (redisUtil.exists(SysConfigConstants.CONFIG_LIST)) {
            Long hashSize = redisUtil.getHashSize(SysConfigConstants.CONFIG_LIST);
            if (hashSize > 0) {
                return;
            }
        }
        LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemConfig::getName, SystemConfig::getValue);
        lqw.eq(SystemConfig::getStatus, false);
        List<SystemConfig> systemConfigList = dao.selectList(lqw);
        systemConfigList.forEach(config -> redisUtil.hset(SysConfigConstants.CONFIG_LIST, config.getName(), config.getValue()));
    }

    /**
     * 通过key数组获取Record对象
     * @param keyList key列表
     * @return MyRecord
     */
    @Override
    public MyRecord getValuesByKeyList(List<String> keyList) {
        if (CollUtil.isEmpty(keyList)) {
            return null;
        }
        MyRecord record = new MyRecord();
        if (!crmebConfig.getAsyncConfig()) {
            LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
            lqw.select(SystemConfig::getName, SystemConfig::getValue);
            lqw.in(SystemConfig::getName, keyList);
            lqw.eq(SystemConfig::getTypeForm,BrandUtil.getBrandIdByUrl());
            lqw.eq(SystemConfig::getStatus, false);
            lqw.groupBy(SystemConfig::getName);
            lqw.orderByDesc(SystemConfig::getId);
            List<SystemConfig> systemConfigList = dao.selectList(lqw);
            keyList.forEach(k -> {
                SystemConfig systemConfig = systemConfigList.stream().filter(config -> config.getName().equals(k)).findFirst().orElse(null);
                if (ObjectUtil.isNotNull(systemConfig)) {
                    record.set(systemConfig.getName(), systemConfig.getValue());
                } else {
                    record.set(k, "");
                }
            });
            return record;
        }
        keyList.forEach(k -> {
            String value = get(k);
            record.set(k, value);
        });
        return record;
    }

    @Override
    public MyRecord getValuesByKeyLists(List<String> keyList,String uri) {
        if (CollUtil.isEmpty(keyList)) {
            return null;
        }
//        String uriDomain = extractDomain(uri);
        MyRecord record = new MyRecord();
        if (!crmebConfig.getAsyncConfig()) {
            LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
            lqw.select(SystemConfig::getName, SystemConfig::getValue);
            lqw.in(SystemConfig::getName, keyList);
            lqw.eq(SystemConfig::getStatus, false);
            lqw.groupBy(SystemConfig::getName);
            lqw.orderByDesc(SystemConfig::getCreateTime);
            Brand brand = brandService.getOne(Wrappers.<Brand>lambdaQuery().eq(Brand::getShareUrl, uri));
            if (brand!=null){
                SystemAdmin admin = adminService.getOne(new LambdaQueryWrapper<SystemAdmin>().eq(SystemAdmin::getBrandId, brand.getId()));
                lqw.eq(SystemConfig::getTypeForm,admin.getId());
//                lqw.eq(SystemConfig::getTypeForm,37);
            }else{
                lqw.eq(SystemConfig::getTypeForm, 0);
            }
            List<SystemConfig> systemConfigList = dao.selectList(lqw);
            keyList.forEach(k -> {
                SystemConfig systemConfig = systemConfigList.stream().filter(config -> config.getName().equals(k)).findFirst().orElse(null);
                if (ObjectUtil.isNotNull(systemConfig)) {
                    record.set(systemConfig.getName(), systemConfig.getValue());
                } else {
                    record.set(k, "");
                }
            });
            return record;
        }
        keyList.forEach(k -> {
            String value = get(k);
            record.set(k, value);
        });
        return record;
    }

    public static String extractDomain(String url) {
        // 找到第一个 "//" 的位置
        int firstSlashIndex = url.indexOf("//") + 2;

        // 找到第二个 "/" 的位置
        int secondSlashIndex = url.indexOf('/', firstSlashIndex);

        // 如果没有找到第二个 "/"，则截取到字符串末尾
        if (secondSlashIndex == -1) {
            return url.substring(firstSlashIndex);
        }

        // 截取从第一个 "//" 后面到第二个 "/" 之间的字符串
        return url.substring(firstSlashIndex, secondSlashIndex);
    }
    /**
     * 根据menu name 获取 value
     *
     * @param name menu name
     * @return String
     */
    @Override
    public String getValueByKey(String name) {
        return get(name);
    }

    @Override
    public String getValueByKeyBrand(String key) {
        return getBrand(key);
    }

    @Override
    public String getValueByKeyBrand(String key, Integer brandId) {
        SystemConfig systemConfig = getByName(key, brandId);
        logger.info("*************systemConfig*************:{}"+systemConfig);
        if (ObjectUtil.isNull(systemConfig) || StrUtil.isBlank(systemConfig.getValue())) {
            return "";
        }
        return systemConfig.getValue();
    }

    /**
     * 品牌商查询配置
     * @param name
     * @return
     */
    /*private String getBrand(String name) {
        SystemAdmin user = SecurityUtil.getLoginUserVo().getUser();
        log.info("#getBrand#查询当前用户信息user={}", JSON.toJSONString(user));
        if (!crmebConfig.getAsyncConfig()) {
            SystemConfig systemConfig = getByName(name,37);
            if (ObjectUtil.isNull(systemConfig) || StrUtil.isBlank(systemConfig.getValue())) {
                return "";
            }
            return systemConfig.getValue();
        }
        Long size = redisUtil.getHashSize(SysConfigConstants.CONFIG_LIST);
        if (size <= 0) {
            SystemConfig systemConfig = getByName(name,37);
            if (ObjectUtil.isNull(systemConfig) || StrUtil.isBlank(systemConfig.getValue())) {
                asyncBlank(name);
                return "";
            }
            async(systemConfig);
            return systemConfig.getValue();
        }
        Object data = redisUtil.hget(SysConfigConstants.CONFIG_LIST, name);
        if (ObjectUtil.isNull(data)) {
            asyncBlank(name);
            return "";
        }
        return data.toString();
    }*/

    private String getBrand(String name) {
//        SystemAdmin user = SecurityUtil.getLoginUserVo().getUser();
//        Integer brandId = BrandUtil.getBrandId();
        Integer brandId = BrandUtil.getBrandIdByUrl();
        SystemConfig systemConfig = getByName(name, brandId);
        if (ObjectUtil.isNull(systemConfig) || StrUtil.isBlank(systemConfig.getValue())) {
            return "";
        }
        return systemConfig.getValue();
    }


    @Override
    public String getValueByKey(String key, Integer brandId) {
        SystemConfig systemConfig = getByName(key, brandId);
        return systemConfig.getValue();
    }

    /**
     * 根据 name 获取 value 找不到抛异常
     *
     * @param name menu name
     * @return String
     */
    @Override
    public String getValueByKeyException(String name) {
        String value = get(name);
        if (StrUtil.isBlank(value)) {
            throw new AppException("没有找到或配置：" + name + "数据");
        }
        return value;
    }

    @Override
    public String getValueByKeyExceptionBrand(String name) {
        String value = getBrand(name);
        if (StrUtil.isBlank(value)) {
            throw new AppException("没有找到或配置：" + name + "数据");
        }
        return value;
    }

    /**
     * 整体保存表单数据
     *
     * @param systemFormCheckRequest SystemFormCheckRequest 数据保存
     * @return boolean
     */
    @Override
    public Boolean saveForm(SystemFormCheckRequest systemFormCheckRequest) {
        // 检测form表单，并且返回需要添加的数据
        systemFormTempService.checkForm(systemFormCheckRequest);

        List<SystemConfig> systemConfigList = new ArrayList<>();
        SystemFormTemp systemFormTemp = systemFormTempService.getById(systemFormCheckRequest.getId());
        // 批量添加
        for (SystemFormItemCheckRequest systemFormItemCheckRequest : systemFormCheckRequest.getFields()) {
            SystemConfig systemConfig = new SystemConfig();
            systemConfig.setName(systemFormItemCheckRequest.getName());
            String value = systemAttachmentService.clearPrefix(systemFormItemCheckRequest.getValue());
            if (StrUtil.isBlank(value)) {
                // 去掉图片域名之后没有数据则说明当前数据就是图片域名
                value = systemFormItemCheckRequest.getValue();
            }
            systemConfig.setValue(value);
            systemConfig.setFormId(systemFormCheckRequest.getId());
            systemConfig.setTitle(systemFormItemCheckRequest.getTitle());
            if (BrandUtil.isBrand()) {
                systemConfig.setTypeForm(BrandUtil.getBrandId());
            } else {
                systemConfig.setTypeForm(0); // 假设0表示平台
            }
            if (systemFormCheckRequest.getId() > 0) {
                systemConfig.setFormName(systemFormTemp.getName());
            }
            systemConfigList.add(systemConfig);
        }

        LambdaQueryWrapper<SystemConfig> oldLqw = Wrappers.lambdaQuery();
        oldLqw.eq(SystemConfig::getFormId, systemFormCheckRequest.getId());
        if (BrandUtil.isBrand()) {
            oldLqw.eq(SystemConfig::getTypeForm, BrandUtil.getBrandId());
        } else {
            oldLqw.eq(SystemConfig::getTypeForm, 0);
        }
            // 删除已经隐藏的数据
        List<SystemConfig> systemConfigOldList = dao.selectList(oldLqw);

        Boolean execute = transactionTemplate.execute(e -> {
            // 删除之前的数据
            if (CollUtil.isNotEmpty(systemConfigOldList)) {
                dao.delete(oldLqw);
            }
            saveOrUpdateBatch(systemConfigList);
            return Boolean.TRUE;
        });
        if (execute) {
            if (crmebConfig.getAsyncConfig()) {
                if (CollUtil.isNotEmpty(systemConfigOldList)) {
                    asyncDelete(systemConfigOldList);
                }
                async(systemConfigList);
            }
        }
        return execute;
    }

    private void asyncDelete(List<SystemConfig> systemConfigList) {
        systemConfigList.forEach(config -> {
            if (redisUtil.exists(config.getName())) {
                redisUtil.hmDelete(SysConfigConstants.CONFIG_LIST, config.getName());
            }
        });
    }

    /**
     * 保存或更新配置数据
     *
     * @param name  菜单名称
     * @param value 菜单值
     * @return boolean
     */
    @Override
    public Boolean updateOrSaveValueByName(String name, String value) {
        value = systemAttachmentService.clearPrefix(value);
        LambdaQueryWrapper<SystemConfig> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(SystemConfig::getName, name);
        lambdaQueryWrapper.eq(SystemConfig::getTypeForm, BrandUtil.getBrandIdByUrl());

        List<SystemConfig> systemConfigs = dao.selectList(lambdaQueryWrapper);
        if (systemConfigs.size() >= 2) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "配置名称存在多个请检查配置 eb_system_config 重复数据：" + name + "条数：" + systemConfigs.size());
        } else if (systemConfigs.size() == 1) {
            SystemConfig systemConfig = systemConfigs.get(0);
            systemConfig.setValue(value);
            if (BrandUtil.isBrand()){
                systemConfig.setTypeForm(BrandUtil.getBrandId());
            }else{
                systemConfig.setTypeForm(0);
            }
            systemConfig.setUpdateTime(new Date());
            boolean update = updateById(systemConfig);
            if (update && crmebConfig.getAsyncConfig()) {
                async(systemConfig);
            }
            return update;
        } else {
            SystemConfig systemConfig = new SystemConfig().setName(name).setValue(value);
            if (BrandUtil.isBrand()){
                systemConfig.setTypeForm(BrandUtil.getBrandId());
            }else{
                systemConfig.setTypeForm(0);
            }
            boolean save = save(systemConfig);
            if (save && crmebConfig.getAsyncConfig()) {
                async(systemConfig);
            }
            return save;
        }
    }

    @Override
    public Boolean updateOrSaveValueByNameBrand(String name, String value) {
        value = systemAttachmentService.clearPrefix(value);
        LambdaQueryWrapper<SystemConfig> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(SystemConfig::getName, name);
        lambdaQueryWrapper.eq(SystemConfig::getTypeForm,BrandUtil.getBrandIdByUrl());
        List<SystemConfig> systemConfigs = dao.selectList(lambdaQueryWrapper);
        if (systemConfigs.size() >= 2) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "配置名称存在多个请检查配置 eb_system_config 重复数据：" + name + "条数：" + systemConfigs.size());
        } else if (systemConfigs.size() == 1) {
            SystemConfig systemConfig = systemConfigs.get(0);
            systemConfig.setValue(value);
            if (BrandUtil.isBrand()){
                systemConfig.setTypeForm(BrandUtil.getBrandId());
            }else{
                systemConfig.setTypeForm(0);
            }
            boolean update = updateById(systemConfig);
            if (update && crmebConfig.getAsyncConfig()) {
                async(systemConfig);
            }
            return update;
        } else {
            SystemConfig systemConfig = new SystemConfig().setName(name).setValue(value);
            if (BrandUtil.isBrand()){
                systemConfig.setTypeForm(BrandUtil.getBrandId());
            }else{
                systemConfig.setTypeForm(0);
            }
            boolean save = save(systemConfig);
            if (save && crmebConfig.getAsyncConfig()) {
                async(systemConfig);
            }
            return save;
        }
    }

    /**
     * 根据formId查询数据
     *
     * @param formId Integer id
     * @return HashMap<String, String>
     */
    @Override
    public HashMap<String, String> info(Integer formId) {
        LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemConfig::getFormId, formId);
        if (BrandUtil.isBrand()){
            lqw.eq(SystemConfig::getTypeForm, BrandUtil.getBrandId());
        }else{
            lqw.eq(SystemConfig::getTypeForm, 0);
        }
        /*if (BrandUtil.isBrand()){
            lqw.ne(SystemConfig::getFormId, 3);
            lqw.ne(SystemConfig::getFormId, 54);
            lqw.ne(SystemConfig::getFormId, 30);
            lqw.eq(SystemConfig::getTypeForm, BrandUtil.getBrandId());
        }else{
            lqw.eq(SystemConfig::getTypeForm, 0);
        }*/
        List<SystemConfig> systemConfigList = dao.selectList(lqw);
        if (ObjectUtil.isNull(systemConfigList)) {
            return CollUtil.newHashMap();
        }
        HashMap<String, String> map = new HashMap<>();
        for (SystemConfig systemConfig : systemConfigList) {
            map.put(systemConfig.getName(), systemConfig.getValue());
        }
        map.put("id", formId.toString());
        return map;
    }

    /**
     * 根据name查询数据
     *
     * @param name name
     * @return boolean
     */
    @Override
    public Boolean checkName(String name) {
        String value = get(name);
        return StrUtil.isBlank(value);
    }

    /**
     * 更新配置信息
     *
     * @param requestList 请求数组
     * @return Boolean
     */
    @Override
    public Boolean updateByList(List<SystemConfigAdminRequest> requestList) {
        List<SystemConfig> configList = requestList.stream().map(e -> {
            SystemConfig systemConfig = new SystemConfig();
            BeanUtils.copyProperties(e, systemConfig);
            return systemConfig;
        }).collect(Collectors.toList());
        boolean batch = updateBatchById(configList);
        if (batch && crmebConfig.getAsyncConfig()) {
            async(configList);
        }
        return batch;
    }

    /**
     * 获取颜色配置
     *
     * @return SystemConfig
     */
    @Override
    public SystemConfig getColorConfig() {
        String colorConfig = getValueByKeyException(SysConfigConstants.CONFIG_CHANGE_COLOR_CONFIG);
        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setName(SysConfigConstants.CONFIG_CHANGE_COLOR_CONFIG);
        systemConfig.setValue(colorConfig);
        return systemConfig;
    }

    private void asyncBlank(String key) {
        redisUtil.hset(SysConfigConstants.CONFIG_LIST, key, "");
    }

    private void async(SystemConfig systemConfig) {
        redisUtil.hset(SysConfigConstants.CONFIG_LIST, systemConfig.getName(), systemConfig.getValue());
    }

    /**
     * 把数据同步到redis
     *
     * @param systemConfigList List<SystemConfig> 需要同步的数据
     */
    private void async(List<SystemConfig> systemConfigList) {
        for (SystemConfig systemConfig : systemConfigList) {
            redisUtil.hset(SysConfigConstants.CONFIG_LIST, systemConfig.getName(), systemConfig.getValue());
        }
    }

    /**
     * 把数据同步到redis
     *
     * @param name String
     * @return String
     */
    private String get(String name) {
        if (!crmebConfig.getAsyncConfig()) {
            SystemConfig systemConfig = getByName(name);
            if (ObjectUtil.isNull(systemConfig) || StrUtil.isBlank(systemConfig.getValue())) {
                return "";
            }
            return systemConfig.getValue();
        }
        Long size = redisUtil.getHashSize(SysConfigConstants.CONFIG_LIST);
        if (size <= 0) {
            SystemConfig systemConfig = getByName(name);
            if (ObjectUtil.isNull(systemConfig) || StrUtil.isBlank(systemConfig.getValue())) {
                asyncBlank(name);
                return "";
            }
            async(systemConfig);
            return systemConfig.getValue();
        }
        Object data = redisUtil.hget(SysConfigConstants.CONFIG_LIST, name);
        if (ObjectUtil.isNull(data)) {
            asyncBlank(name);
            return "";
        }
        return data.toString();
    }

    private SystemConfig getByName(String name) {
        PageHelper.clearPage();
        LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemConfig::getId, SystemConfig::getName, SystemConfig::getValue);
        lqw.eq(SystemConfig::getStatus, false);
        lqw.eq(SystemConfig::getName, name);
        lqw.eq(SystemConfig::getTypeForm, BrandUtil.getBrandIdByUrl());
        lqw.last(" limit 1");
        lqw.orderByDesc(SystemConfig::getCreateTime);
        return getOne(lqw);
    }

    @Override
    public      List<SystemConfig> getSystemConfigs(){
        LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemConfig::getId, SystemConfig::getName, SystemConfig::getValue, SystemConfig::getTypeForm);
        lqw.eq(SystemConfig::getStatus, false);
        lqw.eq(SystemConfig::getName, SysConfigConstants.CONFIG_DIVIDEND);
        lqw.orderByDesc(SystemConfig::getCreateTime);
        return list(lqw);
    }

    private SystemConfig getByName(String name, Integer brandId) {
        PageHelper.clearPage();
        LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemConfig::getId, SystemConfig::getName, SystemConfig::getValue);
        lqw.eq(SystemConfig::getStatus, false);
        lqw.eq(SystemConfig::getName, name);
        lqw.eq(SystemConfig::getTypeForm, brandId);
        lqw.last(" limit 1");
        lqw.orderByDesc(SystemConfig::getCreateTime);
        return getOne(lqw);
    }

    /**
     * 获取各种文字协议
     *
     * @return String
     */
    @Override
    public String getAgreementByKey(String agreementName) {
        if (ObjectUtil.isEmpty(agreementName)) {
            return "Key Not Empty";
        }
        LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemConfig::getName, agreementName);
        lqw.eq(SystemConfig::getStatus, 0);
        lqw.eq(SystemConfig::getTypeForm, BrandUtil.getBrandIdByUrl());
        List<SystemConfig> systemConfigs = dao.selectList(lqw);
        SystemConfig systemConfig = CollUtil.getFirst(systemConfigs);
        if (ObjectUtil.isNull(systemConfig)) {
            return "";
        }
        return systemConfig.getValue();
    }

    /**
     * 获取移动端域名
     * @return 移动端域名
     */
    @Override
    public String getFrontDomain() {
        return getValueByKey(SysConfigConstants.CONFIG_KEY_SITE_URL);
    }

    /**
     * 获取素材域名
     *
     * @return 素材域名
     */
    @Override
    public String getMediaDomain() {
        return systemAttachmentService.getCdnUrl();
    }

    /**
     * 获取主题色
     */
    @Override
    public SystemConfig getChangeColor() {
        return getConfigByNameException(SysConfigConstants.CONFIG_CHANGE_COLOR_CONFIG);
    }

    /**
     * 保存主题色
     */
    @Override
    public Boolean saveChangeColor(SaveConfigRequest request) {
        return updateOrSaveValueByName(SysConfigConstants.CONFIG_CHANGE_COLOR_CONFIG, request.getValue());
    }

    /**
     * 保存家乡购分类
     * @param request
     * @return
     */
    @Override
    public boolean goodsLocationCategorySave(CommonBatchRequest request) {
        SystemConfig systemConfig = getByName(SysConfigConstants.GOODS_LOCATION_CATEGORY);
        if (ObjectUtil.isNull(systemConfig)) {
            systemConfig = new SystemConfig();
            systemConfig.setName(SysConfigConstants.GOODS_LOCATION_CATEGORY);
            systemConfig.setTitle(SysConfigConstants.GOODS_LOCATION_CATEGORY);
            systemConfig.setFormName("家乡购分类配置");
            systemConfig.setValue(CollUtil.join(request.getIdList(), ","));
            systemConfig.setTypeForm(BrandUtil.getBrandIdByUrl());
            save(systemConfig);
        } else {
            SystemConfig systemConfigTmp = new SystemConfig();
            systemConfigTmp.setId(systemConfig.getId());
            systemConfigTmp.setValue(CollUtil.join(request.getIdList(), ","));
            updateById(systemConfigTmp);
        }

        // 商户联盟类型
        updateAllianceTypeIds(request);
        return true;
    }

    /**
     * 商户联盟类型
     * @param request
     */
    private void updateAllianceTypeIds(CommonBatchRequest request) {
        SystemConfig systemConfig = getByName(SysConfigConstants.GOODS_LOCATION_ALLIANCE_TYPE);
        if (ObjectUtil.isNull(systemConfig)) {
            systemConfig = new SystemConfig();
            systemConfig.setName(SysConfigConstants.GOODS_LOCATION_ALLIANCE_TYPE);
            systemConfig.setTitle(SysConfigConstants.GOODS_LOCATION_ALLIANCE_TYPE);
            systemConfig.setFormName("家乡购联盟类型配置");
            systemConfig.setValue(CollUtil.join(request.getAllianceTypeIds(), ","));
            systemConfig.setTypeForm(BrandUtil.getBrandIdByUrl());
            save(systemConfig);
        } else {
            SystemConfig systemConfigTmp = new SystemConfig();
            systemConfigTmp.setId(systemConfig.getId());
            systemConfigTmp.setValue(CollUtil.join(request.getAllianceTypeIds(), ","));
            updateById(systemConfigTmp);
        }
    }

    /**
     * 家乡购分类
     * @return
     */
    @Override
    public List<Integer> getGoodsLocationCategoryList() {
        String value = getValueByKey(SysConfigConstants.GOODS_LOCATION_CATEGORY);
        if (StrUtil.isNotBlank(value)) {
            return Arrays.asList(value.split(",")).stream().map(i -> {
                return Integer.parseInt(i);
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<GoodsLocationResponse> getGoodsLocationCategoryListH5() {
        String value = getValueByKey(SysConfigConstants.GOODS_LOCATION_CATEGORY);
        if (StrUtil.isNotBlank(value)) {
            List<Integer> ids = Arrays.asList(value.split(",")).stream().map(i -> {
                return Integer.parseInt(i);
            }).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(ids)){
                List<MerchantCategory> listByIds = categoryService.getListByIds(ids);
                if(CollUtil.isNotEmpty(listByIds)) {
                    List<GoodsLocationResponse> responseList = listByIds.stream().map(e -> {
                        GoodsLocationResponse articleResponse = new GoodsLocationResponse();
                        BeanUtils.copyProperties(e, articleResponse);
                        return articleResponse;
                    }).collect(Collectors.toList());
                    return responseList;
                }

            }

        }
        return new ArrayList<>();
    }

    @Override
    public List<Integer> goodsLocationAllianceTypeList() {
        String value = getValueByKey(SysConfigConstants.GOODS_LOCATION_ALLIANCE_TYPE);
        if (StrUtil.isNotBlank(value)) {
            return Arrays.asList(value.split(",")).stream().map(i -> {
                return Integer.parseInt(i);
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<GoodsLocationAllianceTypeResponse> getGoodsLocationAllianceTypeListH5() {
        String value = getValueByKey(SysConfigConstants.GOODS_LOCATION_ALLIANCE_TYPE);
        if (StrUtil.isNotBlank(value)) {
            List<Integer> ids = Arrays.asList(value.split(",")).stream().map(i -> {
                return Integer.parseInt(i);
            }).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(ids)) {
                List<MerchantGeneralType> listByIds = merchantGeneralTypeService.getListByIds(ids);
                if (CollUtil.isNotEmpty(listByIds)) {
                    List<GoodsLocationAllianceTypeResponse> responseList = listByIds.stream().map(e -> {
                        GoodsLocationAllianceTypeResponse articleResponse = new GoodsLocationAllianceTypeResponse();
                        BeanUtils.copyProperties(e, articleResponse);
                        return articleResponse;
                    }).collect(Collectors.toList());
                    return responseList;
                }
            }
        }
        return new ArrayList<>();
    }

    @Override
    public List<SystemConfig> getListByBrandId(Integer brandId, List<String> ids) {
        LambdaQueryWrapper<SystemConfig> query = Wrappers.lambdaQuery();
        query.orderByAsc(SystemConfig::getId);
        query.in(SystemConfig::getName, ids);
        query.eq(SystemConfig::getTypeForm, brandId);
        return list(query);
    }

    private SystemConfig getConfigByName(String name) {
        String value = get(name);
        if (StrUtil.isBlank(value)) {
            value = "";
        }
        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setName(name);
        systemConfig.setValue(value);
        return systemConfig;
    }

    private SystemConfig getConfigByNameException(String name) {
        String value = getValueByKeyException(name);
        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setName(name);
        systemConfig.setValue(value);
        return systemConfig;
    }

}

